<script setup lang="ts">
import {computed, reactive} from "vue";
import {ref} from 'vue'
import {type ComponentSize, ElMessage, type FormInstance, type FormRules} from 'element-plus'
import {getSmsCodeApi, smsCodeLoginApi} from "@/api/client/user.ts";
import {setClientToken} from "@/utils/token.ts";
import router from "@/router";

interface SmsLoginForm {
  phone: string
  smsCode: string
}

const formSize = ref<ComponentSize>('large')
const smsLoginFormRef = ref<FormInstance>()
const smsLoginForm = reactive<SmsLoginForm>({
  phone: '',
  smsCode: ''
})

const rules = reactive<FormRules<SmsLoginForm>>({
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur'}
  ],
  smsCode: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur'}
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const token = await smsCodeLoginApi(smsLoginForm.phone, smsLoginForm.smsCode) as any
        setClientToken(token)
        await router.push('/client/home')
      } catch (e: any) {
        ElMessage.error(e)
      }
    } else {
      ElMessage.warning('请输入合法的手机号或验证码')
    }
  })
}

const phoneRegion = ref('+86')

const isCounting = ref(false); // 是否正在倒计时
const countdown = ref(60); // 倒计时时间
const buttonText = computed(() => (isCounting.value ? `${countdown.value}秒后重试` : '获取验证码'));

// 校验手机号是否有效
const isPhoneValid = computed(() => /^1[3-9]\d{9}$/.test(smsLoginForm.phone));

// 处理获取验证码逻辑
const handleGetCode = async () => {
  if (!isPhoneValid.value) {
    return;
  }
  // 发送验证码请求
  try {
    await getSmsCodeApi(smsLoginForm.phone)
    ElMessage.success('验证码发送成功')
    // 禁用按钮并开始倒计时
    isCounting.value = true;
    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value === 0) {
        clearInterval(timer);
        isCounting.value = false;
        countdown.value = 60; // 重置倒计时
      }
    }, 1000);
  } catch (e) {
    ElMessage.error('验证码发送失败')
  }
};

async function redirectPasswordLogin() {
  await router.push('/client/password-login')
}

</script>

<template>
  <div class="container">
    <el-card style="width: 400px">
      <template #header>
        <div class="card-header">
          <span>OJ判题系统</span>
        </div>
      </template>
      <el-form
          ref="smsLoginFormRef"
          style="max-width: 600px"
          :model="smsLoginForm"
          :rules="rules"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >
        <div class="phone">
          <el-select v-model="phoneRegion" placeholder="+86" style="width: 80px">
            <el-option label="+86" value="+86"/>
          </el-select>
          <el-form-item prop="phone">
            <el-input
                v-model="smsLoginForm.phone"
                style="width: 220px"
                placeholder="输入手机号"
            >
            </el-input>
          </el-form-item>
        </div>
        <el-form-item prop="smsCode">
          <el-input
              v-model="smsLoginForm.smsCode"
              style="width: 300px"
              placeholder="验证码"
          >
            <template #append>
              <el-button
                  :disabled="!isPhoneValid || isCounting"
                  :style="{
                    color: isPhoneValid && !isCounting
                        ? '#007AFF'
                        : '#C0C4CC',
                  }"
                  @click="handleGetCode"
              >
                {{ buttonText }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(smsLoginFormRef)">
            登录/注册
          </el-button>
        </el-form-item>
      </el-form>
      <div class="other" @click="redirectPasswordLogin">
        <div>账号密码登录</div>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.container {
  background-color: ghostwhite;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  :deep(.el-card) {
    .card-header {
      text-align: center;
      font-weight: bold;
      font-size: 20px;
    }

    .el-card__body {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;

      .other {
        width: 300px;
        display: flex;
        justify-content: flex-end;
        color: gray;
        margin-top: -10px;
      }

      .other:hover {
        cursor: pointer;
        color: skyblue;
      }
    }

    .el-form {
      .phone {
        width: 300px;
        display: flex;
      }

      .el-form-item:last-child {
        .el-button {
          width: 300px;
          background-color: #242528;
        }
      }
    }
  }
}
</style>